package game;

import java.util.Random;

public class Deck {
	
	/*
	 * list of 52 cards in deck
	 */
	int cards[];
	int deckend;
	
	/*
	 * making new deck with randomly shuffled cards
	 */
	public Deck() {
		deckend=0;
		cards=new int[52];
		for (int i=0;i<52;i++) {
			cards[i]=i;
		}
		Shuffle();
	}
	
	/*
	 * function used to shuffle cards in deck
	 */
	public void Shuffle() {
		Random r=new Random();
		for(int i=0;i<200;i++) {
			int a=r.nextInt(52),b=r.nextInt(52),c;
			c=cards[a];
			cards[a]=cards[b];
			cards[b]=c;
		}
		deckend=0;
	}
	
	/*
	 * only taking cards on game start
	 */
	public int TakeCard() throws BadugiException {
		while(cards[deckend]==52) {
			deckend++;
			if (deckend>51) throw new BadugiException("You have taken too much cards");
		}
		int a=cards[deckend];
		cards[deckend]=52;
		deckend++;
		return a;
	}
	
	/*
	 * only inserting cards after game
	 */
	public void InsertCard(int card) throws BadugiException{
		int i=0;
		while(cards[i]!=52)
		{
			i++;
			if (i>51) throw new BadugiException("you inserted wrong cards");
		}
		cards[i]=card;
	}
	
	/*
	 * exchanging cards in game
	 */
	public int ExchangeCard(int card) {
		if(deckend>51) Shuffle();
		while(cards[deckend]==52) {
			if(deckend==51) Shuffle();
			else deckend++;
		}
		int a=cards[deckend];
		cards[deckend]=card;
		deckend++;
		return a;
	}
	
	static String CardName(int card) throws BadugiException {
		if (card<0 || card>51) throw new BadugiException("Wrong card number");
		String name;
		if (card%13==0) {
			name="A";
		} else if (card%13==1) {
			name="2";
		} else if (card%13==2) {
			name="3";
		} else if (card%13==3) {
			name="4";
		} else if (card%13==4) {
			name="5";
		} else if (card%13==5) {
			name="6";
		} else if (card%13==6) {
			name="7";
		} else if (card%13==7) {
			name="8";
		} else if (card%13==8) {
			name="9";
		} else if (card%13==9) {
			name="10";
		} else if (card%13==10) {
			name="J";
		} else if (card%13==11) {
			name="Q";
		} else {
			name="K";
		}
		if (card%4==0) {
			name+=" C";
		} else if (card%4==1) {
			name+=" D";
		} else if (card%4==2) {
			name+=" H";
		} else {
			name+=" S";
		}
		return name;
	}
}
